package com.yiyi.word_test.service.impl;

import cn.hutool.core.date.DateUtil;
import com.yiyi.word_test.dto.GradeCountDTO;
import com.yiyi.word_test.entity.History;
import com.yiyi.word_test.repository.HistoryRepository;
import com.yiyi.word_test.service.HistoryService;
import com.yiyi.word_test.util.CalculateScoreUtil;
import com.yiyi.word_test.vo.HistoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class HistoryServiceImpl implements HistoryService {

    @Autowired
    private HistoryRepository historyRepository;

    // 保存历史记录
    public History saveHistory(String userOpenid, Integer grade, Integer testScore) {
        History history = new History();
        history.setUserOpenid(userOpenid);
        history.setTestScore(testScore);
        history.setTestGrade(grade);
        return historyRepository.save(history);
    }

    // 计算测试结果
    public Integer calculateScore(GradeCountDTO gradeCountDTO) {
        Integer score = CalculateScoreUtil.calculateScore(gradeCountDTO);
        return score;
    }

    // 获取历史记录
    public List<HistoryVO> getHistory(String userOpenId) {
        List<History> historyList = historyRepository.findByUserOpenidOrderByHistoryIdDesc(userOpenId);
        List<HistoryVO> historyVOList = new ArrayList<>();
        for (History history : historyList) {
            HistoryVO historyVO = new HistoryVO();
            historyVO.setTestScore(history.getTestScore());
            historyVO.setTestTime(DateUtil.format(history.getTestTime(), "yyyy/MM/dd"));
            historyVOList.add(historyVO);
        }
        return historyVOList;
    }
}
